﻿using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using ICSharpCode.SharpZipLib.Zip;
using System.IO;
using System.Text;
using System.Data.OleDb;
using System.Data.Common;
using log4net;
using System.Collections;
using System.Text.RegularExpressions;
using System.Globalization;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using System.Web.Caching;
using System.Collections.Generic;
using System.Collections;
using Telerik.Web.UI;
using System.Net;
using System.Net.Mail;
using System.Linq;
/// <summary>
/// Summary description for Utils
/// </summary>
public class Utils
{
    private static Hashtable hashtable = new Hashtable();
    private static readonly ILog logger = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
    private static Cache cache = HttpContext.Current.Cache;
    public static int flag = 0;
    public static bool selected;
    public static DataTable dt_department; //
    public static int row;

    public Utils()
    {
          
    }
    public static bool IsNumeric(string strToCheck)
    {
        return Regex.IsMatch(strToCheck, @"^[-+]?\d+(\.\d+)?$");
    }
    public static string Right(string value, int length)
    {
        return value.Substring(value.Length - length);
    }
    public static void SendMail(string subject, string body, List<MailAddress> listMailTo, List<MailAddress> listMailCC = null)
    {
        string UserName = "";
        string PassWord = "";
        string EmailSender = "";
        string SMTP_HOST = "";
        string PORT = "25";
        NetworkCredential loginInfo = new NetworkCredential(UserName, PassWord);
        System.Net.Mail.MailMessage msg = new System.Net.Mail.MailMessage();
        msg.From = new MailAddress(EmailSender);
        foreach (var item in listMailTo.Select(x => x.Address).Distinct())
        {
            msg.To.Add(item);
        }
        if (listMailCC != null)
        {
            foreach (var item in listMailCC.Select(x => x.Address).Distinct())
            {   
                msg.CC.Add(item);
            }
        }
        msg.Subject = subject;
        msg.Body = body;
        msg.IsBodyHtml = true;
        SmtpClient client = new SmtpClient(SMTP_HOST);
        client.Port = int.Parse(PORT);
        client.EnableSsl = false;
        client.UseDefaultCredentials = true;
        client.Credentials = loginInfo;
        client.Send(msg);
    }
    public static void SendMail(string subject, string body, string MailTo, List<MailAddress> listMailCC = null)
    {
        string UserName = "";
        string PassWord = "";
        string EmailSender = "";
        string SMTP_HOST = "";
        string PORT = "25";// "587";
        NetworkCredential loginInfo = new NetworkCredential(UserName, PassWord);
        System.Net.Mail.MailMessage msg = new System.Net.Mail.MailMessage();
        msg.From = new MailAddress(EmailSender);
        msg.To.Add(new MailAddress(MailTo));
        if (listMailCC != null)
        {
            //var list = listMailCC.Select(x => x.Address).Distinct();
            foreach (var item in listMailCC.Select(x => x.Address).Distinct())
            {
                msg.CC.Add(item);
            }
        }
        msg.Subject = subject;
        msg.Body = body;
        msg.IsBodyHtml = true;
        SmtpClient client = new SmtpClient(SMTP_HOST);
        client.Port = int.Parse(PORT);
        client.EnableSsl = false;
        client.UseDefaultCredentials = true;
        client.Credentials = loginInfo;
        client.Send(msg);
    }
   
    public static void SendMail(string subject, string body, string MailTo, string MailCC = "")
    {
        string UserName = System.Configuration.ConfigurationManager.AppSettings["SMTPUserName"]; ;
        string PassWord = System.Configuration.ConfigurationManager.AppSettings["SMTPPassWord"]; ;
        string EmailSender = System.Configuration.ConfigurationManager.AppSettings["EmailSender"]; ;
        string SMTP_HOST = System.Configuration.ConfigurationManager.AppSettings["SMTP_HOST"]; ;
        string PORT = System.Configuration.ConfigurationManager.AppSettings["SMTP_PORT"]; ;

        NetworkCredential loginInfo = new NetworkCredential(UserName, PassWord);
        System.Net.Mail.MailMessage msg = new System.Net.Mail.MailMessage();
        msg.From = new MailAddress(EmailSender);
        msg.To.Add(new MailAddress(MailTo));
        if (MailCC != null && MailCC != "")
        {
           msg.CC.Add(new MailAddress(MailCC));
        }
        //msg.To.Add(new MailAddress(email));
        msg.Subject = subject;
        msg.Body = body;
        msg.IsBodyHtml = true;
        SmtpClient client = new SmtpClient(SMTP_HOST);
        client.Port = int.Parse(PORT);
        client.EnableSsl = true;
        client.UseDefaultCredentials = true;
        client.Credentials = loginInfo;
        client.Send(msg);
    }

    public static string getUrlImage()
    {
        return System.Configuration.ConfigurationManager.AppSettings["urlImage"];
    }
    public static void UploadFileToFTP(FileUpload source, string ftpfullpath)
    {
        try
        {
            ftpfullpath = System.Configuration.ConfigurationManager.AppSettings["urlftp"] + ftpfullpath;
            string ftpusername =  System.Configuration.ConfigurationManager.AppSettings["usernameftp"];
            string ftppassword = System.Configuration.ConfigurationManager.AppSettings["passwordftp"];
            string filename = Path.GetFileName(source.FileName);
            FtpWebRequest ftp = (FtpWebRequest)FtpWebRequest.Create(ftpfullpath + filename);
            ftp.Credentials = new NetworkCredential(ftpusername, ftppassword);

            ftp.KeepAlive = true;
            ftp.UseBinary = true;
            ftp.Method = WebRequestMethods.Ftp.UploadFile;
            Stream ftpstream = ftp.GetRequestStream();
            ftpstream.Write(source.FileBytes, 0, source.FileBytes.Length);
            ftpstream.Close();


        }
        catch (Exception ex)
        {
            ControlUtil.LogError("UploadFileToFTP:" + ex.Message);
        }
    }
    public static void DeleteFileFromServer(string filename)
    {
        try
        {
            string ftpfullpath = string.Empty;
            ftpfullpath = System.Configuration.ConfigurationManager.AppSettings["urlftp"] + filename;
            string ftpusername = System.Configuration.ConfigurationManager.AppSettings["usernameftp"];
            string ftppassword = System.Configuration.ConfigurationManager.AppSettings["passwordftp"];
            FtpWebRequest request = (FtpWebRequest)WebRequest.Create(ftpfullpath);
            request.Method = WebRequestMethods.Ftp.DeleteFile;
            request.Credentials = new NetworkCredential(ftpusername, ftppassword);
            FtpWebResponse response = (FtpWebResponse)request.GetResponse();
            response.Close();
        }
        catch (Exception ex)
        {
            ControlUtil.LogError("DeleteFileFromServer:" + ex.Message);
        }
    }
    public static void doSendMailWithAttachment(String Subject, String content, String attachmentFilename, bool isFormatHTML, List<MailAddress> listToEmail, List<MailAddress> listCC = null)
    {
        System.Net.Mail.MailMessage mail = new System.Net.Mail.MailMessage();
        string UserName = "";
        string PassWord = "";
        string EmailSender = "";
        string SMTP_HOST = "";
        string PORT = "25";// "587";
        mail.From = new MailAddress(EmailSender);
        NetworkCredential loginInfo = new NetworkCredential(UserName, PassWord);
        foreach (var item in listToEmail.Select(x => x.Address).Distinct())
        {
            mail.To.Add(item);
        }
        if (listCC != null)
        {
            foreach (var item in listCC.Select(x => x.Address).Distinct())
            {
                mail.CC.Add(item);
            }
        }

        try
        {
            mail.Subject = Subject;
            mail.Body = content;
            mail.IsBodyHtml = isFormatHTML;
            SmtpClient client = new SmtpClient(SMTP_HOST);
            client.Port = int.Parse(PORT);
            client.EnableSsl = false;
            client.UseDefaultCredentials = true;
            client.Credentials = loginInfo;

            if (attachmentFilename != null)
                mail.Attachments.Add(new Attachment(System.Web.HttpContext.Current.Server.MapPath(attachmentFilename)));
            client.Send(mail);
            ControlUtil.Log("Email Class - Sent Success - Email " + mail.To.ToString());
        }
        catch (SmtpException se)
        {
            //logger.Error(se.Message);
            ControlUtil.LogError("Email Class - Send Error - Email: " + mail.To.ToString() + " - Error: " + se.Message);
        }
    }

    public static string KillChars(string strInput)
    {
        if (!String.IsNullOrEmpty(strInput))
        {
            string[] arrBadChars = new string[] { "select", "drop", ";", "--", "insert", "delete", "xp_", "sysobjects", "syscolumns","update","/>","cookie","session",">","script","</" };
            strInput = strInput.Trim().Replace("'", "''");
            strInput = strInput.Replace("%20", " ");
            for (int i = 0; i < arrBadChars.Length; i++)
            {
                strInput = strInput.Replace(arrBadChars[i].ToString(), "");
            }
        }
        return strInput;
    }

    public static Int32 GetUserOnline()
    {
        Int32 userOnline = Membership.Provider.GetNumberOfUsersOnline();
        return userOnline;
    }

    public static void ZipFolder(String folderSrc, String folderZip)
    {
        string[] filenames = Directory.GetFiles(folderSrc);
        using (ZipOutputStream s = new ZipOutputStream(File.Create(folderZip + ".zip")))
        {
            s.SetLevel(9); // 0-9, 9 being the highest level of compression

            byte[] buffer = new byte[4096];

            foreach (string file in filenames)
            {

                ZipEntry entry = new ZipEntry(Path.GetFileName(file));

                entry.DateTime = DateTime.Now;
                s.PutNextEntry(entry);

                using (FileStream fs = File.OpenRead(file))
                {
                    int sourceBytes;
                    do
                    {
                        sourceBytes = fs.Read(buffer, 0, buffer.Length);
                        s.Write(buffer, 0, sourceBytes);

                    } while (sourceBytes > 0);
                }
            }
            s.Flush();
            s.Finish();
            s.Close();
        }

        // clean up files by deleting the temp folder and its content
        // System.IO.Directory.Delete(zip, true);
    }

    public static bool DownloadFile(HttpResponse Response, string filePath)
    {
        System.IO.FileInfo file = new System.IO.FileInfo(filePath);
        string fileName = file.Name;
        // filePath = d:/folder/fileName
        FileStream myFile = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);

        //Reads file as binary values
        BinaryReader _BinaryReader = new BinaryReader(myFile);

        //Ckeck whether user is eligible to download the file
        if (IsEligibleUser())
        {
            //Check whether file exists in specified location
            if (file.Exists)
            {
                try
                {
                    long startBytes = 0;
                    int nDownloadBlock = 0;
                    string lastUpdateTiemStamp = File.GetLastWriteTimeUtc(filePath).ToString("r");
                    string _EncodedData = HttpUtility.UrlEncode(fileName, Encoding.UTF8) + lastUpdateTiemStamp;

                    Response.Clear();
                    Response.Buffer = false;
                    Response.AddHeader("Accept-Ranges", "bytes");
                    Response.AppendHeader("ETag", "\"" + _EncodedData + "\"");
                    Response.AppendHeader("Last-Modified", lastUpdateTiemStamp);
                    Response.ContentType = "application/octet-stream";
                    Response.AddHeader("Content-Disposition", "attachment;filename=" + file.Name);
                    Response.AddHeader("Content-Length", (file.Length - startBytes).ToString());
                    Response.AddHeader("Connection", "Keep-Alive");
                    Response.ContentEncoding = Encoding.UTF8;

                    //Send data
                    _BinaryReader.BaseStream.Seek(startBytes, SeekOrigin.Begin);

                    //Dividing the data in 10000 bytes package
                    nDownloadBlock = 10000; // For small sized file set its file size in
                    int maxCount = (int)Math.Ceiling((file.Length - startBytes + 0.0) / nDownloadBlock);

                    //Download in block of 10000 bytes
                    int i;
                    for (i = 0; i < maxCount && Response.IsClientConnected; i++)
                    {
                        Response.BinaryWrite(_BinaryReader.ReadBytes(nDownloadBlock));
                        Response.Flush();
                    }
                    //if blocks transfered not equals total number of blocks
                    if (i < maxCount)
                        return false;
                    return true;
                }
                catch
                {
                    return false;
                }
                finally
                {
                    Response.End();
                    _BinaryReader.Close();
                    myFile.Close();
                }
            }
        }
        return false;

        //Ex : Utils.downloadFile(Response, Server.MapPath("Download/DOCINSIDE.rar"));
    }//End


    public static void LoadLIstCMCODE(RadComboBox pCtrlName, string strProcedureName)
    {
        try
        {

            DatabaseHelper DB = new DatabaseHelper();
            DataTable dt = DB.ExecuteDataTable(strProcedureName);

            foreach (DataRow row in dt.Rows)
            {
                RadComboBoxItem item = new RadComboBoxItem();
                item.Text = (string)row[0];
                pCtrlName.Items.Add(item);
                item.DataBind();
            }
            dt.Dispose();
        }
        catch (Exception)
        {
        }
    }
    public static void LoadLIstParentID(RadComboBox pCtrlName, string strProcedureName)
    {
        try
        {

            DatabaseHelper DB = new DatabaseHelper();
            DataTable dt = DB.ExecuteDataTable(strProcedureName);

            foreach (DataRow row in dt.Rows)
            {
                RadComboBoxItem item = new RadComboBoxItem();
                item.Text = row[0].ToString();
                pCtrlName.Items.Add(item);
                item.DataBind();
            }
            dt.Dispose();
        }
        catch (Exception)
        {
        }
    }

    public static bool checkUploadFile(HtmlInputFile pControl, Page page, string strServerFolder, string strExtension, int maxSize)
    {

        string getExt = Path.GetExtension(pControl.Value).ToUpper().Trim();
        string strFiletmp = "";
        string strPathDesc = "";

        try
        {
            if (pControl.PostedFile.ContentLength < maxSize)
            {
                if (strExtension.ToUpper().Trim().IndexOf(getExt) == -1)
                    return false;

                strFiletmp = pControl.Value.Trim();
                strFiletmp = Path.GetFileName(strFiletmp);
                if (File.Exists(page.Server.MapPath(".") + strServerFolder + strFiletmp))
                    return false;


                strPathDesc = page.Server.MapPath(".") + "\\" + strServerFolder + "\\" + strFiletmp;
                pControl.PostedFile.SaveAs(strPathDesc);
                System.IO.File.SetAttributes(strPathDesc, System.IO.FileAttributes.Normal);
            }
            else
                return false;

        }

        catch (Exception ex)
        {
            return false;
        }

        

        return true;
    }

    public static void HitCounterWrite(string total)
    {
        try
        {
            System.IO.FileInfo fileInfo = new System.IO.FileInfo(HttpContext.Current.Server.MapPath("Visitor.txt"));
            if (fileInfo.IsReadOnly == true)
            {
                fileInfo.IsReadOnly = false;
            }
            StreamWriter sw = fileInfo.CreateText();
            sw.WriteLine(total);
            sw.Flush();
            sw.Close();
        }
        catch (Exception)
        {

        }
        /*
        TextWriter tw = new StreamWriter(HttpContext.Current.Server.MapPath("Visitor.txt"));
        tw.WriteLine(total);
        tw.Flush();
        tw.Close();
         * */
       // StreamWriter sw = new StreamWriter(HttpContext.Current.Server.MapPath("Visitor.txt"));
       // sw.WriteLine(total);
       // sw.Flush();
       // sw.Close();
    }

    public static string HitCounterRead()
    {
        string result = "0";
        try
        {
            //TextWriter tw = new StreamWriter("date.txt");
            StreamReader sr = File.OpenText(HttpContext.Current.Server.MapPath("Visitor.txt"));
            result = sr.ReadLine();
            sr.Close();
        }
        catch (Exception)
        {
            
        }
        return result;
    }

    public static string UploadDocument(HtmlInputFile flpPic, Page page, string strServerFolder)
    {
        List<string> exts = new List<string>() { ".doc", ".docx", ".rtf", ".txt", ".xls", ".xlsx", ".pdf", ".wmv", ".mpg", ".flv", ".avi" };
        bool kt = false;
        if (exts.Contains(Path.GetExtension(flpPic.Value).ToLower()))
        {
            kt = true;
        }
        try
        {
            if (flpPic.PostedFile.ContentLength != 0 && kt)
            {
                string filename = Path.GetFileName(flpPic.PostedFile.FileName);
                string path = page.Server.MapPath(".") + "\\" + strServerFolder + "\\" + filename;
                if (File.Exists(path))
                {
                    return "File đã được tải. Vui lòng chọn file khác!";
                }
                flpPic.PostedFile.SaveAs(path);
                System.IO.File.SetAttributes(path, System.IO.FileAttributes.Normal);

                return "Thành công";
            }
            else
            {
                return "Vui lòng chọn file tài liệu hoặc video!";
            }
        }
        catch (Exception exp)
        {
            string strErr = exp.Message;
            return "Đường dẫn chứa file không hợp lệ. Vui lòng xem lại." + strErr;
        }
    }
    public static string UploadFile(HtmlInputFile pControl, Page page, string strServerFolder, string strExtension)
    {
        if (Path.GetExtension(pControl.Value).ToUpper().Trim() != strExtension.ToUpper().Trim())
        {
            return "File phải được định dạng là file " + strExtension;
        }
        string strFiletmp = "";
        string strPathDesc = "";
        try
        {
            if (pControl.Value != "")
            {
                strFiletmp = pControl.Value.Trim();
                strFiletmp = Path.GetFileName(strFiletmp);
                if (File.Exists(page.Server.MapPath(".") + strServerFolder + strFiletmp))
                {
                    return "File đã được tải. Vui lòng chọn file khác!";
                }
                strPathDesc = page.Server.MapPath(".") + "\\" + strServerFolder + "\\" + strFiletmp;
                pControl.PostedFile.SaveAs(strPathDesc);
                System.IO.File.SetAttributes(strPathDesc, System.IO.FileAttributes.Normal);
            }
            else
            {
                return "Vui lòng chọn file!";
            }
        }
        catch (Exception exp)
        {
            string strErr = exp.Message;
            return "Đường dẫn chứa file không hợp lệ. Vui lòng xem lại.";
        }
        return "Thành công!";

        /*Ex: 
         * <input id="File1" style="width: 288px" type="file" runat="server" />
         * Utils.UploadFile(this.File1, this.Page, "Upload", ".xls");
         * */
    }

    public static string UploadFile(HtmlInputFile file, Page page , string strServerFolder, string strExtension, string UserName, int MaxSize) // Upload nhieu dinh dang va gioi han dung luong file return duong dan luu tren server
    {

        string[] arryExtension = strExtension.Split(';');
        string getExt = Path.GetExtension(file.Value).ToUpper().Trim();
        string strFiletmp = "";
        string strPathDesc = "";
        string strDate = DateTime.Now.Day+ DateTime.Now.Month + DateTime.Now.Year.ToString();
        if (file.PostedFile.ContentLength < MaxSize)
        {
            foreach (string word in arryExtension)
            {
                if (getExt == word.ToUpper().Trim())
                {
                    try
                    {
                        strFiletmp =  file.Value.Trim();
                        strFiletmp = Path.GetFileName(UserName + strDate + strFiletmp);
                        strFiletmp = UserName + strDate + strFiletmp;
                        if (File.Exists(page.Server.MapPath(strFiletmp)))
                        {
                            return "";
                        }
                        //strFiletmp = strFiletmp;
                        /*
                        strPathDesc = page.Server.MapPath(strServerFolder + "/" + strFiletmp);
                        fUpload.SaveAs(strPathDesc);
                        System.IO.File.SetAttributes(strPathDesc, System.IO.FileAttributes.Normal);*/
                        strPathDesc = page.Server.MapPath(".") + "\\" + strServerFolder + "\\" + strFiletmp;
                        file.PostedFile.SaveAs(strPathDesc);
                        System.IO.File.SetAttributes(strPathDesc, System.IO.FileAttributes.Normal);
                    }
                    catch (Exception exp)
                    {
                        string strErr = exp.Message;
                        return "";
                    }
                }
            }
            return strFiletmp;
        }
        else
            return "";
        /*
        string[] arryExtension = strExtension.Split(';');
        //string getExt = Path.GetExtension(pControl.Value).ToUpper().Trim();
        string getExt = System.IO.Path.GetExtension(fUpload.FileName.ToUpper());
        string strFiletmp = "";
        string strPathDesc = "";
        if (fUpload.PostedFile.ContentLength < MaxSize)
        {
            foreach (string word in arryExtension)
            {
                if (getExt == word.ToUpper().Trim())
                {
                    try
                    {
                        strFiletmp = fUpload.FileName;
                        strFiletmp = Path.GetFileName(strFiletmp);
                        if (File.Exists(page.Server.MapPath(strFiletmp)))
                        {
                            return "";
                        }
                        strFiletmp = UserName + "_" + strFiletmp;
                        strPathDesc = page.Server.MapPath(strServerFolder+"/"+ strFiletmp);
                        fUpload.SaveAs(strPathDesc);
                        System.IO.File.SetAttributes(strPathDesc, System.IO.FileAttributes.Normal);
                    }
                    catch (Exception exp)
                    {
                        string strErr = exp.Message;
                        return "";
                    }
                }
            }
            return strFiletmp;
        }
        else
            return "";*/
        
    }

    public static string UploadFile(HtmlInputFile file, Page page, string strServerFolder, string strExtension, string UserName) // Upload nhieu dinh dang return duong dan luu tren server
    {

        string[] arryExtension = strExtension.Split(';');
        string getExt = Path.GetExtension(file.Value).ToUpper().Trim();        
        string strFiletmp = "";
        string strPathDesc = "";
        string strDate = DateTime.Now.Day + DateTime.Now.Month + DateTime.Now.Year.ToString();
        foreach (string word in arryExtension)
        {
            if (getExt == word.ToUpper().Trim())
            {
                try
                {
                    strFiletmp = file.Value.Trim();
                    strFiletmp = Path.GetFileName(strFiletmp);
                    strFiletmp = UserName + strDate + strFiletmp;
                    FileInfo theFile = new FileInfo(page.Server.MapPath(strServerFolder + strFiletmp));
                    if (theFile.Exists)
                    {
                        theFile.Delete();
                    }
                    
                    //strFiletmp = strFiletmp;
                    /*
                    strPathDesc = page.Server.MapPath(strServerFolder + "/" + strFiletmp);
                    fUpload.SaveAs(strPathDesc);
                    System.IO.File.SetAttributes(strPathDesc, System.IO.FileAttributes.Normal);*/
                    strPathDesc = page.Server.MapPath(".") + "\\" + strServerFolder + "\\" + strFiletmp;
                    file.PostedFile.SaveAs(strPathDesc);
                    System.IO.File.SetAttributes(strPathDesc, System.IO.FileAttributes.Normal);
                }
                catch (Exception exp)
                {
                    string strErr = exp.Message;
                    return "";
                }
            }
        }
        return strServerFolder + strFiletmp;
    }
        
    // Check User Is Logging ?
    public static bool IsEligibleUser()
    {
        return true;
    }

    public static string ConvertDMYtoMDY(string pDDMMYY)
    {
        string temp_Date = pDDMMYY.Trim();
        string mstr_ShortDate = temp_Date.Substring(0, temp_Date.LastIndexOf("/") + 5);
        return mstr_ShortDate.Substring(mstr_ShortDate.IndexOf("/") + 1, mstr_ShortDate.LastIndexOf("/") - mstr_ShortDate.IndexOf("/") - 1) + "/" + mstr_ShortDate.Substring(0, mstr_ShortDate.IndexOf("/")) + "/" + mstr_ShortDate.Substring(mstr_ShortDate.LastIndexOf("/") + 1, mstr_ShortDate.Length - mstr_ShortDate.LastIndexOf("/") - 1);
    }

    public static string ConvertDMYtoMMMddyyyy(string pDDMMYY)
    {
        System.DateTime mDateID = new System.DateTime();
        mDateID = Convert.ToDateTime(ConvertDMYtoMDY(pDDMMYY));

        return mDateID.ToString("MMM dd yyyy");
    }
    public static string ConvertMDYtoDMY(object pMMDDYY)
    {
        if (pMMDDYY.ToString().Trim() != "")
        {
            return Convert.ToDateTime(pMMDDYY.ToString().Trim()).ToString("dd/MM/yy");
        }
        else
            return "";
    }

    public static string ConvertMDYtoDDMMYYYY(object pMMDDYY)
    {
        if (pMMDDYY.ToString().Trim() != "")
        {
            return Convert.ToDateTime(pMMDDYY.ToString().Trim()).ToString("dd/MM/yyyy");
        }
        else
            return "";
    }

    public static string ConvertDMYtoMDY(object pDDMMYY)
    {
        if (pDDMMYY.ToString().Trim() != "")
        {
            return Convert.ToDateTime(pDDMMYY.ToString().Trim()).ToString("MM/dd/yy");
        }
        else
            return "";
    }

    public static string ConvertDMYtoMMDDYYYY(object pDDMMYY)
    {
        if (pDDMMYY.ToString().Trim() != "")
        {
            return Convert.ToDateTime(pDDMMYY.ToString().Trim()).ToString("MM-dd-yyyy");
        }
        else
            return "";
    }

    public static string ConvertDMYtoMMDDYYYYHHMM(object pDDMMYY,object pHH,object pMM)
    {
        if (pDDMMYY.ToString().Trim() != "" && pHH.ToString().Trim() != "" && pMM.ToString().Trim() != "")
        {
            return Convert.ToDateTime(pDDMMYY.ToString().Trim()).ToString("MM-dd-yyyy " + pHH.ToString().Trim() + ":" + pMM.ToString().Trim());
        }
        else
            return "";
    }

    public static string ConvertDMYtoDDMMYYYY(object pDDMMYY)
    {
        if (pDDMMYY.ToString().Trim() != "")
        {
            return Convert.ToDateTime(pDDMMYY.ToString().Trim()).ToString("dd-MMM-yyyy");
        }
        else
            return "";
    }

    public static string ConvertDDMMYYYYtoDMY(object pDDMMMYYYY)
    {
        if (pDDMMMYYYY.ToString().Trim() != "")
        {
            return Convert.ToDateTime(pDDMMMYYYY.ToString().Trim()).ToString("dd/MM/yyyy");
        }
        else
            return "";
    }
     
    /// LOAD YEAR TO COMBOBOX
    public static void LoadYearToList(DropDownList pCtrlName, int pMinYear, int pMaxYear)
    {
        for (int i = pMinYear; i <= pMaxYear; i++)
        {
            pCtrlName.Items.Add(new ListItem(Convert.ToString(i).Trim(), Convert.ToString(i).Trim()));
        }
    }

    /// LOAD YEAR TO COMBOBOX
    public static void LoadYearToList(DropDownList pCtrlName, int pMinYear)
    {
        int pMaxYear = DateTime.Now.Year;
        for (int i = pMinYear; i <= pMaxYear; i++)
        {
            pCtrlName.Items.Add(new ListItem(Convert.ToString(i).Trim(), Convert.ToString(i).Trim()));
        }
    }

    /// LOAD MONTH TO COMBOBOX
    public static void LoadMonthToList(DropDownList pCtrlName)
    {
        pCtrlName.Items.Add(new ListItem("01", "1"));
        pCtrlName.Items.Add(new ListItem("02", "2"));
        pCtrlName.Items.Add(new ListItem("03", "3"));
        pCtrlName.Items.Add(new ListItem("04", "4"));
        pCtrlName.Items.Add(new ListItem("05", "5"));
        pCtrlName.Items.Add(new ListItem("06", "6"));
        pCtrlName.Items.Add(new ListItem("07", "7"));
        pCtrlName.Items.Add(new ListItem("08", "8"));
        pCtrlName.Items.Add(new ListItem("09", "9"));
        pCtrlName.Items.Add(new ListItem("10", "10"));
        pCtrlName.Items.Add(new ListItem("11", "11"));
        pCtrlName.Items.Add(new ListItem("12", "12"));
    }

    /// LOAD DAY TO COMBOBOX
    public static void LoadDayToList(DropDownList pCtrlName)
    {
        for (int i = 1; i < 32; i++)
        {
            string temp = i < 10 ? "0" + i.ToString() : i.ToString();
            pCtrlName.Items.Add(new ListItem(temp, i.ToString()));
        }
    }

    //Load Week to COMBOX
    public static void LoadWeekToList(DropDownList pCtrlName)
    {
        System.DateTime today = new System.DateTime(System.DateTime.Today.Ticks);
        System.DateTime Dautuan = new System.DateTime();
        System.DateTime Cuoituan = new System.DateTime();
        System.DateTime ThangTuan = new System.DateTime();


        int iDay = today.Day;
        ThangTuan = today.AddDays(7 * 4);
        string strDate;
        string DayOfWeek = today.DayOfWeek.ToString();
        int iDayofWeek = GetDayOfWeek(DayOfWeek);

        //			double i;
        //			i = iDay - 30;
        for (int i = 0; i < 60; i += 7)
        {
            Dautuan = ThangTuan.AddDays(-(iDayofWeek - 2) - i);
            Cuoituan = Dautuan.AddDays(6);

            strDate = Dautuan.Date.ToString("dd/MM/yyyy") + "->" + Cuoituan.Date.ToString("dd/MM/yyyy");
            pCtrlName.Items.Add(new ListItem(strDate, strDate));
        }
    }

    //Get Thu cua Tuan
    public static int GetDayOfWeek(string strinput)
    {
        switch (strinput)
        {
            case "Sunday":
                return 1;
            case "Monday":
                return 2;
            case "Tuesday":
                return 3;
            case "Wednesday":
                return 4;
            case "Thursday":
                return 5;
            case "Friday":
                return 6;
            case "Saturday":
                return 7;
        }
        return 0;
    }


    public static void ShowMessageBox(System.Web.UI.Page pPage, string pMessage)
    {

        string strScript = "<script language=JavaScript>";
        strScript += "alert('" + pMessage + "');";
        strScript += "</script>";

        if (!pPage.IsStartupScriptRegistered("clientScript"))
        {
            pPage.RegisterStartupScript("clientScript", strScript);
        }

        //Ex Utils.ShowMessageBox(this.Page, "Hello Honglk");
    }

    //Alert Message and refhesh
    public static void ShowMessageBoxAndRefresh(System.Web.UI.Page pPage, string pMessage)
    {
        string pageName = Path.GetFileNameWithoutExtension(pPage.AppRelativeVirtualPath);
        string pageNameFull = Path.GetFileName(pPage.AppRelativeVirtualPath);

        string strScript = "<script language=JavaScript>";
        strScript += "alert('" + pMessage + "');";
        strScript += "window.location ='" + pageNameFull + "'";
        strScript += "</script>";

        if (!pPage.IsStartupScriptRegistered("clientScript"))
        {
            pPage.RegisterStartupScript("clientScript", strScript);
        }

        //Ex Utils.ShowMessageBox(this.Page, "Hello Honglk");
    }

    public static void ShowMessageBoxAndRefresh(System.Web.UI.Page pPage, string pMessage, string url)
    {

        string strScript = "<script language=JavaScript>";
        strScript += "alert('" + pMessage + "');";
        strScript += "window.location ='" + url + "'";
        strScript += "</script>";

        if (!pPage.IsStartupScriptRegistered("clientScript"))
        {
            pPage.RegisterStartupScript("clientScript", strScript);
        }

        //Ex Utils.ShowMessageBox(this.Page, "Hello Honglk");
    }

    public static int SafeDataInteger(Object pValue)
    {
        if ((pValue is DBNull))
        {
            return 0;
        }
        else if (Convert.ToString(pValue) == "")
        {
            return 0;
        }
        return Convert.ToInt32(pValue);
    }

    public static string GetLanguage(HttpRequest Request, System.Web.SessionState.HttpSessionState Session)
    {
        string lang = "vi";
        if (string.IsNullOrEmpty(Request["Lang"]))
        {
            /*
            if (Session["Lang"] == null)
            {
                lang = "vi";
            }
            else
            {
                lang = Session["Lang"].ToString();
            }
            */
            lang = "vi";
        }
        else
        {
            lang = Request["Lang"];
        }
        return lang;

        //Ex Utils.GetLanguage(Request,Session);
    }

    public static string GetCulture(HttpRequest Request, System.Web.SessionState.HttpSessionState Session)
    {
        string culture = "vi-VN";
        string lang = "";
        if (string.IsNullOrEmpty(Request["Lang"]))
        {
            lang = "vi";
            /*
            if (Session["Lang"] == null)
            {
                lang = "vi";
            }
            else
            {
                lang = Session["Lang"].ToString();
            }
             */
        }
        else
        {
            lang = Request["Lang"];
        }
        culture = lang.Equals("vi") ? "vi-VN" : "en-US";
        return culture;
    }

    public static void LoadDataToList(RadComboBox pCtrlName, string strProcedureName)
    {
        try
        {
            pCtrlName.Items.Clear();
            DatabaseHelper DB = new DatabaseHelper();
            DataTable dt = DB.ExecuteDataTable(strProcedureName);

            foreach (DataRow row in dt.Rows)
            {
                RadComboBoxItem item = new RadComboBoxItem();
                item.Text = (string)row[1];
                item.Value = row[0].ToString();
                pCtrlName.Items.Add(item);
                item.DataBind();
            }
            dt.Dispose();
        }
        catch (Exception)
        {
        }
    }

    public static void LoadDataToList(RadComboBox pCtrlCode, RadComboBox pCtrlName, string strProcedureName, DatabaseHelper DB, int HasChooseAll=0)
    {
        try
        {
            DataTable dt = DB.ExecuteDataTable(strProcedureName, CommandType.StoredProcedure, ConnectionState.CloseOnExit);
            if (HasChooseAll == 1)//ADD THEM ITEM "TAT CA"
            {
                DataRow dr = dt.NewRow();
                dr[0] = "";
                dr[1] = "-- Tất cả --";
                dt.Rows.InsertAt(dr, 0);
            }
            foreach (DataRow row in dt.Rows)
            {
                RadComboBoxItem itemCode = new RadComboBoxItem();

                itemCode.Text = row[0].ToString();
                itemCode.Value = (string)row[1];
                pCtrlCode.Items.Add(itemCode);

                RadComboBoxItem itemName = new RadComboBoxItem();

                itemName.Text = (string)row[1];
                itemName.Value = row[0].ToString();
                pCtrlName.Items.Add(itemName);

                itemCode.DataBind();
                itemName.DataBind();
            }
            dt.Dispose();
        }
        catch (Exception ex)
        {
        }
    }
    /// <summary>
    /// load data to radcombobox telerik
    /// </summary>
    /// <param name="cboName"></param>
    /// <param name="strProcedureName"></param>
    public static void LoadDataToCombo(RadComboBox cboName, string strProcedureName, DbType CodeType = DbType.String ,int HasChooseAll = 0)
    {
        try
        {
            DatabaseHelper DB = new DatabaseHelper();
            DataTable dt = DB.ExecuteDataTable(strProcedureName);
            /*
            DataTable dt = new DataTable();
            if (CacheUtil.GetCache(cboName.ToString()) == null)
            {
                dt = DB.ExecuteDataTable(strProcedureName);
            }
            else
            {
               dt =  (DataTable)CacheUtil.GetCache(cboName.ToString());
            }
            */
            if (HasChooseAll == 1)
            {
                DataRow dr = dt.NewRow();
                dr["Code"] = "-1";
                dr["Name"] = "-- Tất cả --";
                dt.Rows.InsertAt(dr, 0);
            }
            if (HasChooseAll == 2)
            {
                DataRow dr = dt.NewRow();
                if (CodeType == DbType.String)
                {
                    dr["Code"] = "none";
                    dr["Name"] = "-- Không có --";
                }
                else if (CodeType == DbType.Int32)
                {
                    dr["Code"] = 0;
                    dr["Name"] = "-- Không có --";
                }

                dt.Rows.InsertAt(dr, 0);
            }

            foreach (DataRow row in dt.Rows)
            {
                RadComboBoxItem ra = new RadComboBoxItem();
                ra.Text = row[1].ToString();
                ra.Value = row[0].ToString();
                cboName.Items.Add(ra);
            }
            dt.Dispose();
        }
        catch (Exception)
        {
        }
    }
    public static void loadEmployeeToCombo(RadComboBox cboEmployee,int roleID = 0, int ShopID=0,Int16 isAll = 0)
    {
        DBDataContext db = LINQUtil.GetDBWriteOnly();
        //cboProduct
        var list = (from p in db.Employees
                    where p.Status == 'A' && (p.RoleID == roleID || roleID == 0)
                    && (p.ShopID == ShopID || ShopID == 0)
                    orderby p.EmployeeCode
                    select new
                    {
                        p.EmployeeCode,
                        p.EmplyeeName,
                        p.ID
                    }).ToList();
        cboEmployee.Items.Clear();

        if (isAll != 0)
        {
            RadComboBoxItem ra = new RadComboBoxItem();
            ra.Text = "---Chọn---";
            ra.Value = "0";
            cboEmployee.Items.Add(ra);
        }
        foreach (var p in list)
        {
            RadComboBoxItem ra = new RadComboBoxItem();
            ra.Text = p.EmployeeCode + "-" + p.EmplyeeName;
            ra.Value = p.ID.ToString();
            cboEmployee.Items.Add(ra);
        }
    }

    public static void loadProductToComboForStamp(RadComboBox cboProduct, Int16 isAll = 0)
    {
        DBDataContext db = LINQUtil.GetDBWriteOnly();
        var listProduct = (from p in db.Products
                          from pack in db.CodeDetails
                          where p.Status == 'A'
                          && pack.CMCode == "PackType"
                          && pack.Status == 'A'
                          && p.ProductType == "R"
                          && pack.CDCode != "1"
                          orderby p.ProductName,pack.CDCode
                          select new
                          {
                              ProductID = p.ID,
                              p.ProductName,
                              PackTypeName = pack.CDName,
                              PackType = pack.CDCode

                          }).ToList();
        cboProduct.Items.Clear();

        if (isAll != 0)
        {
            RadComboBoxItem ra = new RadComboBoxItem();
            ra.Text = "---Chọn---";
            ra.Value = "";
            cboProduct.Items.Add(ra);
        }

        foreach (var p in listProduct)
        {
            RadComboBoxItem ra = new RadComboBoxItem();
            ra.Text = p.ProductName + " (" + p.PackTypeName + ")";
            ra.Value = p.ProductID.ToString() + "|" + p.PackType.ToString();
            cboProduct.Items.Add(ra);
        }
    }
    public static void loadProductToCombo(RadComboBox cboProduct, Int16 isAll = 0, string strProductType = "R",int ShopID=0)
    {
        DBDataContext db = LINQUtil.GetDBWriteOnly();
        var listProduct = db.Combo_Product(strProductType, ShopID).ToList();
        cboProduct.Items.Clear();

        if (isAll != 0)
        {
            RadComboBoxItem ra = new RadComboBoxItem();
            ra.Text = "---Chọn---";
            ra.Value = "";
            cboProduct.Items.Add(ra);
        }
        if (strProductType != "R")
        {
            foreach (var p in listProduct)
            {
                RadComboBoxItem ra = new RadComboBoxItem();
                ra.Text = p.ProductName + " - " + p.Quantity;
                ra.Value = p.ProductID.ToString() ;
                cboProduct.Items.Add(ra);
            }
        }
        else
        {
            foreach (var p in listProduct)
            {
                RadComboBoxItem ra = new RadComboBoxItem();
                // ra.Text = p.ProductCode +" - " + p.ProductName +" - "+p.PackTypeName+" - "+p.Quantity;
                ra.Text = p.ProductName + " (" + p.PackTypeName + " -SL tồn kho " + p.Quantity + ")";
                ra.Value = p.ProductID.ToString() + "|" + p.PackType.ToString();
                cboProduct.Items.Add(ra);
            }
        }
    }
    public static void loadProductToComboSearch(RadComboBox cboProduct, Int16 isAll = 0, string strProductType = "")
    {
        DBDataContext db = LINQUtil.GetDBWriteOnly();
        //cboProduct
        var listProduct = (from p in db.Products
                           where p.Status == 'A' && (p.ProductType == strProductType || strProductType== "")
                           orderby p.ProductCode
                           select new
                           {
                               p.ProductCode,
                               p.ProductName,
                               p.ID
                           }).ToList();
        cboProduct.Items.Clear();

        if (isAll != 0)
        {
            RadComboBoxItem ra = new RadComboBoxItem();
            ra.Text = "---Tất cả---";
            ra.Value = "";
            cboProduct.Items.Add(ra);
        }
        foreach (var p in listProduct)
        {
            RadComboBoxItem ra = new RadComboBoxItem();
            ra.Text = p.ProductCode + "-" + p.ProductName;
            ra.Value = p.ID.ToString();
            cboProduct.Items.Add(ra);
        }
    }
    public static void loadProductPurchaseOrder(RadComboBox cboProduct, Int16 isAll = 0, string strProductType = "")
    {
        DBDataContext db = LINQUtil.GetDBWriteOnly();
        //cboProduct
        if (strProductType == "P")
        {
            var listProduct = (from p in db.Products
                               where p.Status == 'A' && (p.ProductType == strProductType || strProductType == "")
                               orderby p.ProductCode
                               select new
                               {
                                   p.ProductCode,
                                   p.ProductName,
                                   p.ID
                               }).ToList();
            cboProduct.Items.Clear();

            if (isAll != 0)
            {
                RadComboBoxItem ra = new RadComboBoxItem();
                ra.Text = "---Chọn---";
                ra.Value = "";
                cboProduct.Items.Add(ra);
            }
            foreach (var p in listProduct)
            {
                RadComboBoxItem ra = new RadComboBoxItem();
                ra.Text = p.ProductCode + "-" + p.ProductName;
                ra.Value = p.ID.ToString() + "|0";
                cboProduct.Items.Add(ra);
            }
        }
        if (strProductType == "R")
        {
            var listProduct = (from p in db.Products
                               from pack in db.CodeDetails
                               where p.Status == 'A'
                               && pack.CMCode == "PackType"
                               && pack.Status == 'A'
                               && p.ProductType == "R"
                               orderby p.ProductName, pack.CDCode
                               select new
                               {
                                   ProductID = p.ID,
                                   p.ProductName,
                                   p.ProductCode,
                                   PackTypeName = pack.CDName,
                                   PackType = pack.CDCode

                               }).ToList();
            cboProduct.Items.Clear();

            if (isAll != 0)
            {
                RadComboBoxItem ra = new RadComboBoxItem();
                ra.Text = "---Chọn---";
                ra.Value = "";
                cboProduct.Items.Add(ra);
            }

            foreach (var p in listProduct)
            {
                RadComboBoxItem ra = new RadComboBoxItem();
                ra.Text = p.ProductCode + "-" + p.ProductName + " (" + p.PackTypeName +")";
                ra.Value = p.ProductID.ToString() + "|" + p.PackType.ToString();
                cboProduct.Items.Add(ra);
            }
        }
    }
    public static void loadProductToComboPrice(RadComboBox cboProduct, Int16 isAll = 0, string strProductType = "")
    {
        DBDataContext db = LINQUtil.GetDBWriteOnly();
        //cboProduct
        var listProduct = (from p in db.Products
                           where p.Status == 'A' && (p.ProductType == strProductType || strProductType == "")
                           orderby p.ProductCode
                           select new
                           {
                               p.ProductCode,
                               p.ProductName,
                               p.ID
                           }).ToList();
        cboProduct.Items.Clear();

        if (isAll != 0)
        {
            RadComboBoxItem ra = new RadComboBoxItem();
            ra.Text = "---Chọn---";
            ra.Value = "";
            cboProduct.Items.Add(ra);
        }
        foreach (var p in listProduct)
        {
            RadComboBoxItem ra = new RadComboBoxItem();
            ra.Text = p.ProductCode + "-" + p.ProductName;
            ra.Value = p.ID.ToString();
            cboProduct.Items.Add(ra);
        }
    }
    public static void loadLocationToRadListBox(RadListBox rlbLocation)
    {
        DBDataContext db = LINQUtil.GetDBWriteOnly();
        //cboProduct
        var listProduct = (from p in db.Locations
                           where p.Status == 'A' && p.ParentID == 0
                           orderby p.LocationName
                           select new
                           {
                               p.LocationName,
                               p.ID
                           }).ToList();
        rlbLocation.Items.Clear();

        //if (isAll != 0)
        //{
        //    r ra = new RadComboBoxItem();
        //    ra.Text = "---Chọn---";
        //    ra.Value = "";
        //    cbLocation.Items.Add(ra);
        //}

        foreach (var p in listProduct)
        {
            RadListBoxItem ra = new RadListBoxItem();
            ra.Text = p.LocationName;
            ra.Value = p.ID.ToString();
            rlbLocation.Items.Add(ra);
        }
    }
    public static void loadShopToRadListBox(RadListBox rlbObj, int ProvinceID = 0, int ShopID = 0, string ShopType = "")
    {
        DBDataContext db = LINQUtil.GetDBWriteOnly();
        var listProduct = (from p in db.Shops
                           where p.Status == 'A'
                           && (p.ProvinceID == ProvinceID || ProvinceID == 0)
                           && (p.ID == ShopID || ShopID == 0)
                           && (p.ShopType == ShopType || ShopType == "")
                           orderby p.ShopCode
                           select new
                           {
                               p.ShopCode,
                               p.ShopName,
                               p.ID
                           }).ToList();
        rlbObj.Items.Clear();
        //if (isAll != 0)
        //{
        //    RadComboBoxItem ra = new RadComboBoxItem();
        //    ra.Text = "---Tất cả---";
        //    ra.Value = "-1";
        //    cboShop.Items.Add(ra);
        //}

        if (listProduct.Count <= 1)
            rlbObj.Items.Clear();

        foreach (var p in listProduct)
        {
            RadListBoxItem ra = new RadListBoxItem();
            ra.Text = p.ShopCode + "-" + p.ShopName;
            ra.Value = p.ID.ToString();

            rlbObj.Items.Add(ra);
        }
    }
    public static void loadLocation(RadComboBox obj, int iParentID = 0, int isAll = 0,int provinceID=0)
    {
        DBDataContext db = LINQUtil.GetDBWriteOnly();
        //cboProduct
        var listProduct = (from p in db.Locations
                           where p.Status == 'A' && p.ParentID == iParentID
                           && (p.ID == provinceID || provinceID == 0)
                           orderby p.LocationName
                           select new
                           {
                               p.LocationName,
                               p.ID
                           }).ToList();
        obj.Items.Clear();

        if (isAll != 0)
        {
            RadComboBoxItem ra = new RadComboBoxItem();
            ra.Text = "---Chọn---";
            ra.Value = "0";
            obj.Items.Add(ra);
        }
        if(listProduct.Count <= 1)
            obj.Items.Clear();
        foreach (var p in listProduct)
        {
            RadComboBoxItem ra = new RadComboBoxItem();
            ra.Text = p.LocationName;
            ra.Value = p.ID.ToString();
            obj.Items.Add(ra);
        }
    }
    public static void loadLocationSearch(RadComboBox obj, int iParentID = 0, int isAll = 0, int provinceID = 0)
    {
        DBDataContext db = LINQUtil.GetDBWriteOnly();
        //cboProduct
        var listProduct = (from p in db.Locations
                           where p.Status == 'A' && p.ParentID == iParentID
                           && (p.ID == provinceID || provinceID == 0)
                           orderby p.LocationName
                           select new
                           {
                               p.LocationName,
                               p.ID
                           }).ToList();
        obj.Items.Clear();

        if (isAll != 0)
        {
            RadComboBoxItem ra = new RadComboBoxItem();
            ra.Text = "---Tất cả---";
            ra.Value = "0";
            obj.Items.Add(ra);
        }
        if (listProduct.Count <= 1)
            obj.Items.Clear();
        foreach (var p in listProduct)
        {
            RadComboBoxItem ra = new RadComboBoxItem();
            ra.Text = p.LocationName;
            ra.Value = p.ID.ToString();
            obj.Items.Add(ra);
        }
    }
    public static int CaculateWarehouse(DBDataContext db, int iShopID, int iProductID, int iPackType, int iQuantity, string strUserName, Double dPurchasePrice, string PageName)
    {
        //DBDataContext db = new DBDataContext();
        int iReturn = 1;
        try
        {
            //Caculate: Quantity
            var checkExistsProduct = (from c in db.Warehouses
                                      where c.ProductID == iProductID
                                            && c.ShopID == iShopID
                                            && c.PackType == iPackType
                                            && c.Status == 'A'
                                      select c).FirstOrDefault();
            if (checkExistsProduct == null)//ProductID chua ton tai thi Insert Warehouse
            {
                Warehouse objWarehouse = new Warehouse();
                objWarehouse.ProductID = iProductID;
                objWarehouse.ShopID = iShopID;
                objWarehouse.PackType = iPackType;
                objWarehouse.PurchasePrice = dPurchasePrice;
                objWarehouse.Quantity = iQuantity;
                objWarehouse.CreatedBy = strUserName;
                objWarehouse.CreatedDateTime = DateTime.Now;
                objWarehouse.LastUpdatedBy = strUserName;
                objWarehouse.LastUpdatedDateTime = DateTime.Now;
                objWarehouse.Status = 'A';
                db.Insert<Warehouse>(objWarehouse);
                //db.SubmitChanges();
            }
            else //ProductID  ton tai thi Update Quantity, PurchasePrice: Warehouse
            {
                //Caculate: Quantity
                checkExistsProduct.Quantity = checkExistsProduct.Quantity + iQuantity;
                if (checkExistsProduct.Quantity <= 0)// so luong = 0
                {
                    dPurchasePrice = 0;
                }
                else
                {
                    double dOldPurchasePrice = Convert.ToDouble(checkExistsProduct.PurchasePrice);
                    checkExistsProduct.PurchasePrice = dOldPurchasePrice == 0 ? dPurchasePrice : (dOldPurchasePrice + dPurchasePrice) / 2;
                }
                //db.SubmitChanges();
            }
        }
        catch (Exception ex)
        {
            ControlUtil.LogError(PageName + " Page-CaculateWarehouse:" + ex.Message);
            iReturn = 0;
        }
        return iReturn;
    }

    public static void loadProductType(RadComboBox cboProductType, Int16 isAll = 0, string strType = "T")
    {
        DBDataContext db = LINQUtil.GetDBWriteOnly();
        //cboProduct
        var listProduct = (from p in db.ProductTypes
                           where p.Status == 'A' && p.Type == strType
                           orderby p.Name
                           select p).ToList();
        cboProductType.Items.Clear();

        if (isAll != 0)
        {
            RadComboBoxItem ra = new RadComboBoxItem();
            ra.Text = "---Chọn---";
            ra.Value = "-1";
            cboProductType.Items.Add(ra);
        }
        foreach (ProductType p in listProduct)
        {
            RadComboBoxItem ra = new RadComboBoxItem();
            ra.Text  = p.Name;
            ra.Value = p.ID.ToString();
            cboProductType.Items.Add(ra);
        }
    }
    public static void loadProductGifToCombo(RadComboBox cboProduct, Int16 isAll = 0)
    {
        DBDataContext db = LINQUtil.GetDBWriteOnly();
        //cboProduct
        var listProduct = (from p in db.Products
                           where p.Status == 'A' && p.ProductType == "P"
                           orderby p.ProductCode
                           select p).ToList();
        cboProduct.Items.Clear();

        if (isAll != 0)
        {
            RadComboBoxItem ra = new RadComboBoxItem();
            ra.Text = "---Chọn---";
            ra.Value = "0";
            cboProduct.Items.Add(ra);
        }
        foreach (Product p in listProduct)
        {
            RadComboBoxItem ra = new RadComboBoxItem();
            ra.Text = p.ProductCode + "-" + p.ProductName;
            ra.Value = p.ID.ToString();
            cboProduct.Items.Add(ra);
        }
    }
    public static void loadShopToCombo(RadComboBox cboShop, int isAll = 0, int ShopID = 0, string ShopType = "")
    {
        DBDataContext db = LINQUtil.GetDBWriteOnly();
        //cboShop
       
        var listProduct = (from p in db.Shops
                           where p.Status == 'A'
                           && (p.ID == ShopID || ShopID ==0)
                           && (p.ShopType == ShopType || ShopType == "")
                           orderby p.ShopCode
                           select new{
                               p.ShopCode,
                               p.ShopName,
                               p.ID
                           }).ToList();
        cboShop.Items.Clear();
        if (isAll != 0)
        {
            RadComboBoxItem ra = new RadComboBoxItem();
            ra.Text = "---Chọn---";
            ra.Value = "0";
            cboShop.Items.Add(ra);
        }
        foreach (var p in listProduct)
        {
            RadComboBoxItem ra = new RadComboBoxItem();
            ra.Text = p.ShopCode + "-" + p.ShopName;
            ra.Value = p.ID.ToString();
            cboShop.Items.Add(ra);
        }
    }

    public static void loadShopByProvinceToCombo(RadComboBox cboShop, int isAll = 0, int ProvinceID = 0,int ShopID=0, string ShopType = "")
    {
        DBDataContext db = LINQUtil.GetDBWriteOnly();
        //cboShop

        var listProduct = (from p in db.Shops
                           where p.Status == 'A'
                           && (p.ProvinceID == ProvinceID || ProvinceID == 0)
                           && (p.ID == ShopID || ShopID == 0)
                           && (p.ShopType == ShopType || ShopType == "")
                           orderby p.ShopCode
                           select new
                           {
                               p.ShopCode,
                               p.ShopName,
                               p.ID
                           }).ToList();
        cboShop.Items.Clear();
        if (isAll != 0)
        {
            RadComboBoxItem ra = new RadComboBoxItem();
            ra.Text = "---Chọn---";
            ra.Value = "0";
            cboShop.Items.Add(ra);
        }

        if (listProduct.Count <= 1)
            cboShop.Items.Clear();

        foreach (var p in listProduct)
        {
            RadComboBoxItem ra = new RadComboBoxItem();
            ra.Text = p.ShopCode + "-" + p.ShopName;
            ra.Value = p.ID.ToString();
            cboShop.Items.Add(ra);
        }
    }
    public static void loadShopByProvinceToComboSearch(RadComboBox cboShop, int isAll = 0, int ProvinceID = 0, int ShopID = 0, string ShopType = "")
    {
        DBDataContext db = LINQUtil.GetDBWriteOnly();
        //cboShop

        var listProduct = (from p in db.Shops
                           where p.Status == 'A'
                           && (p.ProvinceID == ProvinceID || ProvinceID == 0)
                           && (p.ID == ShopID || ShopID == 0)
                           && (p.ShopType == ShopType || ShopType == "")
                           orderby p.ShopCode
                           select new
                           {
                               p.ShopCode,
                               p.ShopName,
                               p.ID
                           }).ToList();
        cboShop.Items.Clear();
        if (isAll != 0)
        {
            RadComboBoxItem ra = new RadComboBoxItem();
            ra.Text = "---Tất cả---";
            ra.Value = "-1";
            cboShop.Items.Add(ra);
        }

        if (listProduct.Count <= 1)
            cboShop.Items.Clear();
        
        foreach (var p in listProduct)
        {
            RadComboBoxItem ra = new RadComboBoxItem();
            ra.Text = p.ShopCode + "-" + p.ShopName;
            ra.Value = p.ID.ToString();
            cboShop.Items.Add(ra);
        }
    }
    public static void loadShopToComboSearch(RadComboBox cboShop, Int16 isAll = 0, int ShopID = 0, string ShopType = "")
    {
        DBDataContext db = LINQUtil.GetDBWriteOnly();
        //cboShop
        var listProduct = (from p in db.Shops
                           where p.Status == 'A'
                           && (p.ID == ShopID || ShopID == 0)
                           && (p.ShopType == ShopType || ShopType == "")
                           orderby p.ShopCode
                           select new
                           {
                               p.ShopName,
                               p.ShopCode,
                               p.ID
                           }).ToList();
        cboShop.Items.Clear();
        if (isAll != 0)
        {
            RadComboBoxItem ra = new RadComboBoxItem();
            ra.Text = "---Tất cả---";
            ra.Value = "-1";
            cboShop.Items.Add(ra);
        }
        foreach (var p in listProduct)
        {
            RadComboBoxItem ra = new RadComboBoxItem();
            ra.Text = p.ShopCode + "-" + p.ShopName;
            ra.Value = p.ID.ToString();
            cboShop.Items.Add(ra);
        }
    }
    public static void loadShopToComboExcludeID(RadComboBox cboShop, Int16 isAll = 0, int excludeShopID = 0, string ShopType = "")
    {
        DBDataContext db = LINQUtil.GetDBWriteOnly();
        //cboShop
        var listProduct = (from p in db.Shops
                           where p.Status == 'A'
                           && (p.ID != excludeShopID || excludeShopID == 0)
                           && (p.ShopType == ShopType || ShopType == "")
                           orderby p.ShopCode
                           select p).ToList();
        cboShop.Items.Clear();
        if (isAll != 0)
        {
            RadComboBoxItem ra = new RadComboBoxItem();
            ra.Text = "---Chọn---";
            ra.Value = "0";
            cboShop.Items.Add(ra);
        }
        if (listProduct.Count <= 1)
            cboShop.Items.Clear();
        foreach (Shop p in listProduct)
        {
            RadComboBoxItem ra = new RadComboBoxItem();
            ra.Text = p.ShopCode + "-" + p.ShopName;
            ra.Value = p.ID.ToString();
            cboShop.Items.Add(ra);
        }
    }
    public static void loadShopToComboExcludeSearch(RadComboBox cboShop, Int16 isAll = 0, int excludeShopID = 0, string ShopType = "")
    {
        DBDataContext db = LINQUtil.GetDBWriteOnly();
        //cboShop
        var listProduct = (from p in db.Shops
                           where p.Status == 'A'
                           && (p.ID != excludeShopID || excludeShopID == 0)
                           && (p.ShopType == ShopType || ShopType == "")
                           orderby p.ShopCode
                           select p).ToList();
        cboShop.Items.Clear();
        if (isAll != 0)
        {
            RadComboBoxItem ra = new RadComboBoxItem();
            ra.Text = "---Tất cả---";
            ra.Value = "0";
            cboShop.Items.Add(ra);
        }
        if (listProduct.Count <= 1)
            cboShop.Items.Clear();
        foreach (Shop p in listProduct)
        {
            RadComboBoxItem ra = new RadComboBoxItem();
            ra.Text = p.ShopCode + "-" + p.ShopName;
            ra.Value = p.ID.ToString();
            cboShop.Items.Add(ra);
        }
    }
    public static void loadVendorToCombo(RadComboBox cboVendor, Int16 isAll = 0)
    {
        DBDataContext db = LINQUtil.GetDBWriteOnly();
        //cboShop
        var listProduct = (from p in db.Vendors
                           where p.Status == 'A'
                           orderby p.VendorCode
                           select p).ToList();
        cboVendor.Items.Clear();
        if (isAll != 0)
        {
            RadComboBoxItem ra = new RadComboBoxItem();
            ra.Text = "---Chọn---";
            ra.Value = "-1";
            cboVendor.Items.Add(ra);
        }
        foreach (Vendor p in listProduct)
        {
            RadComboBoxItem ra = new RadComboBoxItem();
            ra.Text = p.VendorCode + "-" + p.VendorName;
            ra.Value = p.ID.ToString();
            cboVendor.Items.Add(ra);
        }
    }
    public static void LoadDataFromDataTable(RadComboBox cboName, DataTable dt, DbType CodeType = DbType.String, int HasChooseAll = 0)
    {
        try
        {
            
            if (HasChooseAll == 1)
            {
                DataRow dr = dt.NewRow();
                dr[0] = "-1";
                dr[1] = "-- Tất cả --";
                dt.Rows.InsertAt(dr, 0);
            }
            if (HasChooseAll == 2)
            {
                DataRow dr = dt.NewRow();
                if (CodeType == DbType.String)
                {
                    dr[0] = "none";
                    dr[1] = "-- Không có --";
                }
                else if (CodeType == DbType.Int32)
                {
                    dr[0] = 0;
                    dr[1] = "-- Không có --";
                }

                dt.Rows.InsertAt(dr, 0);
            }

            foreach (DataRow row in dt.Rows)
            {
                RadComboBoxItem ra = new RadComboBoxItem();
                ra.Value = row[0].ToString();
                ra.Text = row[1].ToString();
                cboName.Items.Add(ra);
            }
            dt.Dispose();
        }
        catch (Exception)
        {
        }
    }
   
    public static void LoadDataToRadioButtonList(RadioButtonList rblName, string strProcedureName)
    {
        try
        {

            DatabaseHelper DB = new DatabaseHelper();
            DataTable dt = DB.ExecuteDataTable(strProcedureName);
            foreach (DataRow row in dt.Rows)
            {
                rblName.Items.Add(new ListItem(row[1].ToString(), row[0].ToString()));
            }
            dt.Dispose();
        }
        catch (Exception)
        {
        }
    }
    public static void LoadDataToListBox(ListBox pCtrlName, string strProcedureName)
    {
        try
        {

            DatabaseHelper DB = new DatabaseHelper();
            DataTable dt = DB.ExecuteDataTable(strProcedureName);
            foreach (DataRow row in dt.Rows)
            {
                pCtrlName.Items.Add(new ListItem(row[1].ToString(), row[0].ToString()));
            }
            dt.Dispose();
        }
        catch (Exception)
        {
        }
    }

    public static void LoadDataToCheckBoxList(CheckBoxList cbList, string strProcedureName)
    {
        try
        {

            DatabaseHelper DB = new DatabaseHelper();
            DataTable dt = DB.ExecuteDataTable(strProcedureName);
            foreach (DataRow row in dt.Rows)
            {
                cbList.Items.Add(new ListItem(row[1].ToString(), row[0].ToString()));
            }
            dt.Dispose();
        }
        catch (Exception)
        {
        }
    }

    public static void LoadCodeDetail(RadComboBox cboObject, string CMCode, int HasChooseAll=0)
    {
        try
        {
            DatabaseHelper DB = new DatabaseHelper();
            DataTable dt = new DataTable();
            DbParameter paramCMCode = DB.Parameter;
            
            paramCMCode.ParameterName = "CMCode";
            paramCMCode.DbType = DbType.String;
            paramCMCode.Value = CMCode;

            DB.AddParameter(paramCMCode);
            dt = DB.ExecuteDataTable("CodeDetail_LoadtoCombo", CommandType.StoredProcedure, ConnectionState.CloseOnExit);

            if (HasChooseAll == 1)//ADD THEM ITEM "TAT CA"
            {
                DataRow dr = dt.NewRow();
                dr["Code"] = "";
                dr["Name"] = "-- Tất cả --";
                dt.Rows.InsertAt(dr, 0);
            }

            if (HasChooseAll == 2)//ADD THEM ITEM "KHONG CO"
            {
                DataRow dr = dt.NewRow();
                dr["Code"] = "none";
                dr["Name"] = "-- Không có --";
                dt.Rows.InsertAt(dr, 0);
            }
            if (HasChooseAll == 3)//ADD THEM ITEM "CHỌN"
            {
                DataRow dr = dt.NewRow();
                dr["Code"] = "";
                dr["Name"] = "-- Chọn --";
                dt.Rows.InsertAt(dr, 0);
            }
            
        //    cboObject.DataSource = dt;
        ////    cboObject.DataBind();
        //    cboObject.DataTextField = "Name";
        //    cboObject.DataValueField = "Code";

            //huy them vao tranh tinh trạng combobox load bi loi  khoa Đatabindin lai
            foreach (DataRow row in dt.Rows)
            {
                RadComboBoxItem ra = new RadComboBoxItem();
                ra.Text = row[1].ToString();
                ra.Value = row[0].ToString();
                cboObject.Items.Add(ra);
            }
            dt.Dispose();
        }
        catch (Exception)
        {
        }
    }
    public static void LoadDataToGrid(DataGrid dtgGrid, string strProcedureName)
    {
        DatabaseHelper DB = new DatabaseHelper();
        DataTable dt = DB.ExecuteDataTable(strProcedureName);
        DataView dv = new DataView(dt);
        dtgGrid.DataSource = dv;
        dtgGrid.DataBind();
        dtgGrid.Columns[0].Visible = false;
        // dtgGrid.Items[0].Visible = false;
    }

    public static int RandomNumber(int min, int max)
    {
        Random random = new Random();
        return random.Next(min, max);
    }

    public static string RandomString(int size, bool lowerCase)
    {
        StringBuilder builder = new StringBuilder();
        Random random = new Random();
        char ch;
        for (int i = 0; i < size; i++)
        {
            ch = Convert.ToChar(Convert.ToInt32(Math.Floor(26 * random.NextDouble() + 65)));
            builder.Append(ch);
        }
        if (lowerCase)
            return builder.ToString().ToLower();
        return builder.ToString();
    }

    public static string GetPassword()
    {
        StringBuilder builder = new StringBuilder();
        builder.Append(RandomString(4, true));
        builder.Append(RandomNumber(1000, 9999));
        builder.Append(RandomString(2, false));
        return builder.ToString();
    }

    public static string ActiceCode(int size)
    {
        StringBuilder builder = new StringBuilder();
        builder.Append(RandomString(size, true));
        builder.Append(RandomNumber(1000, 9999));
        builder.Append(RandomString(size, false));
        return builder.ToString();
    }

    public static bool IsValidEmailAddress(string sEmail)
    {
        if (sEmail == null)
        {
            return false;
        }

        int nFirstAT = sEmail.IndexOf('@');
        int nLastAT = sEmail.LastIndexOf('@');

        if ((nFirstAT > 0) && (nLastAT == nFirstAT) &&
        (nFirstAT < (sEmail.Length - 1)))
        {
            // address is ok regarding the single @ sign
            return (Regex.IsMatch(sEmail, @"(\w+)@(\w+)\.(\w+)"));
        }
        else
        {
            return false;
        }
    }

    public static void OpenNewWindow(System.Web.UI.Page pPage, string pURL, string pTitle)
    {
        string strScript = "<script language=JavaScript>";
        strScript += "window.open('" + pURL + "','" + pTitle + "')";
        strScript += "</script>";
        if (!pPage.IsStartupScriptRegistered("clientScript"))
            pPage.RegisterStartupScript("clientScript", strScript);
    }
    public static void OpenNewWindowPopup(System.Web.UI.Page pPage, string pURL, string pTitle)
    {
        string strScript = "<script language=JavaScript>";
        strScript += "ShowDialog('" + pURL + "','" + pTitle + "')";
        strScript += "</script>";
        if (!pPage.IsStartupScriptRegistered("clientScript"))
            pPage.RegisterStartupScript("clientScript", strScript);
    }

    public static string checkFileSize(FileUpload fUploadResume, int p)
    {
        throw new NotImplementedException();
    }

    public static void LoadExperience(DropDownList pCtrlName)
    {
        for (int i = 0; i <= 20; i++)
        {
            pCtrlName.Items.Add(new ListItem(i.ToString(), i.ToString()));
        }
    }

    
    public static string RemoveUnicode(string s)
    {
        string stFormD = s.Normalize(NormalizationForm.FormD);
        StringBuilder sb = new StringBuilder();

        for (int ich = 0; ich < stFormD.Length; ich++)
        {
            UnicodeCategory uc = CharUnicodeInfo.GetUnicodeCategory(stFormD[ich]);
            if (uc != UnicodeCategory.NonSpacingMark)
            {
                sb.Append(stFormD[ich]);
            }
        }
        return (sb.ToString().Normalize(NormalizationForm.FormC));
    }
    public static void getCookie(string strURl)
    {
        HttpCookie appCookie = new HttpCookie("URL");
        appCookie.Value = strURl;
        appCookie.Expires = DateTime.Now;
    }

    public static int dateDiff(String datePart, DateTime startDate, DateTime endDate)
    {
        int result = 0;
        TimeSpan timeSpan = endDate.Subtract(startDate);
        if (datePart.ToUpper().Equals("HOUR"))
        {
            result = timeSpan.Hours;
        }
        else if (datePart.ToUpper().Equals("MINUTE"))
        {
            result = timeSpan.Minutes;
        }
        else if (datePart.ToUpper().Equals("SECOND"))
        {
            result = timeSpan.Seconds;
        }
        return result;
    }

    public static double DatimeTounix(DateTime datetime)
    {
        double result = 0;
        TimeSpan span = (datetime - new DateTime(1970, 1, 1, 0, 0, 0, 0));
        try
        {
            result = (double)span.TotalSeconds;
        }
        catch (Exception ex)
        {
            logger.Error(ex);
        }
        return result;
    }
    public static DateTime unixToDatetime(double unix)
    {
        DateTime dateTime = new System.DateTime(1970, 1, 1, 0, 0, 0, 0);
        try
        {
            dateTime = dateTime.AddSeconds(unix);
        }
        catch (Exception ex)
        {
            logger.Error(ex);
        }
        return dateTime;

    }
    public static void moveFile(string srcFile, String descFile)
    {
        try
        {
            if (File.Exists(descFile))
            {
                File.Delete(descFile);
            }
            File.Move(srcFile, descFile);
        }

        catch (FileNotFoundException ex)
        {
            logger.Error(ex);
            logger.Error("File " + srcFile + " khong ton tai");
        }

    }
    public static void copyFile(string srcFile, String descFile)
    {
        try
        {
                File.Copy(srcFile, descFile, true);
        }
        catch (FileNotFoundException ex)
        {
            logger.Error(ex);
            logger.Error("File " + srcFile + " khong ton tai");
        }

    }
    public void createFolder(String pathFolder)
    {
        if (!Directory.Exists(pathFolder))
        {
            DirectoryInfo dir1 = new DirectoryInfo(pathFolder);
            dir1.Create();
        }
    }

    public static string getParameter(HttpRequest Request, int index)
    {
        string param = Request["param"];
                      
        string parameter = "";
        try
        {
            //   Admin/Home/1 
            string[] arrParam = param.Split('/');
            parameter = arrParam[index];
        }catch(Exception){
            parameter = "";
        }
        return parameter;
    }

    public static void insertCache(string cacheName, object value, int timeSpan =10,bool force = false)
    {
        if (force == false)
        {
            if (cache[cacheName] != null)
            {
                cache.Insert(cacheName, value, null, DateTime.MaxValue, TimeSpan.FromMinutes(timeSpan));
            }
        }
        else
        {
            cache.Insert(cacheName, value, null, DateTime.MaxValue, TimeSpan.FromMinutes(timeSpan));
        }
    }

    public static object getCache(string cacheName){

        object result = cache[cacheName];
        if (result != null)
        {
            return result;
        }
        else
        {
            result = "";
        }
        return result;
    }

    public static void loadLocation(RadComboBox cboName, int parentID, Int16 isAll = 0, int arg = 1)
    {
        DBDataContext db = LINQUtil.GetDBWriteOnly();
        if (arg == 1)//Tinh Thanhf
        {
            var list = (from l in db.Locations where l.Status == 'A' && l.ParentID == 0 select l).ToList();
            cboName.Items.Clear();

            if (isAll != 0)
            {
                RadComboBoxItem ra = new RadComboBoxItem();
                ra.Text = "---Chọn---";
                ra.Value = "0";
                cboName.Items.Add(ra);
            }
            foreach (Location p in list)
            {
                RadComboBoxItem ra = new RadComboBoxItem();
                ra.Text = p.LocationName;
                ra.Value = p.ID.ToString();
                cboName.Items.Add(ra);
            }
        }
        else // Quan/Huyen
        {
            var list = (from l in db.Locations where l.Status == 'A' && l.ParentID == parentID && l.ParentID != 0 select l).ToList();
            cboName.Items.Clear();

            if (isAll != 0)
            {
                RadComboBoxItem ra = new RadComboBoxItem();
                ra.Text = "---Chọn---";
                ra.Value = "0";
                cboName.Items.Add(ra);
            }
            foreach (Location p in list)
            {
                RadComboBoxItem ra = new RadComboBoxItem();
                ra.Text = p.LocationName;
                ra.Value = p.ID.ToString();
                cboName.Items.Add(ra);
            }
        }
    }
    
    
   
    public static void LoadTimeCombo(DropDownList dr, string strTime)
    {
        string strNumber = "0";
        if (strTime.ToLower().Equals("h"))
        {
            for (int i = 0; i <= 23; i++)
            {
                if (i < 10)
                    dr.Items.Add(new ListItem(strNumber + i.ToString(), strNumber + i.ToString()));
                else
                    dr.Items.Add(new ListItem(i.ToString(), i.ToString()));
            }
        }
        else if (strTime.ToLower().Equals("m")) {
            for (int i = 0; i <= 59; i++)
            {
                if (i < 10)
                    dr.Items.Add(new ListItem(strNumber + i.ToString(), strNumber + i.ToString()));
                else
                    dr.Items.Add(new ListItem(i.ToString(), i.ToString()));
            }
        }
    }

    #region Encrypt - Decrypt Functions
    public static string Encrypt(string original)
    {
        return Encrypt(original, "!@#$%^&*()~_+|");
    }

    public static string Encrypt(string original, string key)
    {
        TripleDESCryptoServiceProvider objDESProvider;
        MD5CryptoServiceProvider objHashMD5Provider;
        byte[] keyhash;
        byte[] buffer;
        try
        {
            objHashMD5Provider = new MD5CryptoServiceProvider();
            keyhash = objHashMD5Provider.ComputeHash(UnicodeEncoding.Unicode.GetBytes(key));
            objHashMD5Provider = null;

            objDESProvider = new TripleDESCryptoServiceProvider();
            objDESProvider.Key = keyhash;
            objDESProvider.Mode = CipherMode.ECB;

            buffer = UnicodeEncoding.Unicode.GetBytes(original);
            return Convert.ToBase64String(objDESProvider.CreateEncryptor().TransformFinalBlock(buffer, 0, buffer.Length));
        }
        catch
        {
            return string.Empty;
        }
    }

    public static string Decrypt(string encrypted)
    {
        return Decrypt(encrypted, "!@#$%^&*()~_+|");
    }

    public static string Decrypt(string encrypted, string key)
    {
        TripleDESCryptoServiceProvider objDESProvider;
        MD5CryptoServiceProvider objHashMD5Provider;
        byte[] keyhash;
        byte[] buffer;

        try
        {
            objHashMD5Provider = new MD5CryptoServiceProvider();
            keyhash = objHashMD5Provider.ComputeHash(UnicodeEncoding.Unicode.GetBytes(key));
            objHashMD5Provider = null;

            objDESProvider = new TripleDESCryptoServiceProvider();
            objDESProvider.Key = keyhash;
            objDESProvider.Mode = CipherMode.ECB;

            buffer = Convert.FromBase64String(encrypted);
            return UnicodeEncoding.Unicode.GetString(objDESProvider.CreateDecryptor().TransformFinalBlock(buffer, 0, buffer.Length));
        }
        catch
        {
            return string.Empty;
        }
    }
    #endregion

    #region Menu
    public static string GetURL(string ID)
    {
        DatabaseHelper db = new DatabaseHelper();
        DbParameter paramID = db.Parameter;
        if (ID == null) ID ="48";
        paramID.ParameterName = "ID";
        paramID.DbType = DbType.Int32;
        paramID.Value = Int32.Parse(ID);
        db.AddParameter(paramID);
        DataTable dt = db.ExecuteDataTable("Menu_GetURL", CommandType.StoredProcedure, ConnectionState.CloseOnExit);
        if (dt.Rows.Count != 0)
        {
            return dt.Rows[0][0].ToString();
        }
        else
        {
            paramID.Value = 48;
            dt = db.ExecuteDataTable("Menu_GetURL", CommandType.StoredProcedure, ConnectionState.CloseOnExit);
            return dt.Rows[0][0].ToString();
        }
    }

    public static string GetURL1(string FunctionID, string UserID)
    {
        DatabaseHelper db = new DatabaseHelper();
        DbParameter paramFunctionID = db.Parameter;
        if (FunctionID == null) FunctionID = "48";
        paramFunctionID.ParameterName = "FunctionID";
        paramFunctionID.DbType = DbType.Int32;
        paramFunctionID.Value = Int32.Parse(FunctionID);
        db.AddParameter(paramFunctionID);

        DbParameter paramUserID = db.Parameter;
        if (UserID == null) UserID = "-1";
        paramUserID.ParameterName = "UserID";
        paramUserID.DbType = DbType.Int32;
        paramUserID.Value = Int32.Parse(UserID);
        db.AddParameter(paramUserID);

        DataTable dt = db.ExecuteDataTable("MenuGetURL", CommandType.StoredProcedure, ConnectionState.CloseOnExit);
        if (dt.Rows.Count != 0)
        {
            return dt.Rows[0][0].ToString();
        }
        else
        {
            return "0";
        }
    }
    #endregion
}
